package com.lepu.app.main.activity;

import java.util.HashMap;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.app.utils.AppEnterTongJi;
import com.app.utils.AppWebChromClient;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.SdLocal;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserLocaljsObject;
import com.core.lib.utils.BrowserLocaljsObject.BrowserLocaljsObjectDelegate;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.CustomWebView;
import com.eyzhs.app.R;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

/*
 * 自定义浏览器
 */
public class AppBroswerActivity extends AppBroswerActivityBase implements
        OnTopbarNewLeftLayoutListener, BrowserWebClientDelegate,BrowserWebChromeDelegate
        , AsyncRequest, BrowserLocaljsObjectDelegate {

    private static final String REQUEST_TEST = "request_test";

    //===================================
    private CustomWebView mWebView = null;
    private ProgressBar mProgressBar = null;
    private CustomTopBarNew mTopbar = null;
    private ImageView mShareImageView = null;

    private boolean mNeedShare = false;
    private String mShareObjectID = "";
    private int mShareObjectType = 0;
    private String mTopbarTitle = "";
    @SuppressWarnings("unused")
    private int mFromType = Const.AppBroswerType.TYPE_DEFAULT;

    //self 赋值
    private String mShareTitle = "";
    private String mShareUrl = "";
    private String mShareInfo = "";
    private String mShareCover = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedDefaultUmeng = false;
        mNeedStatusBar = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_broswer_activity);

        init();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onResume() {
        mWebView.onResume();
        super.onResume();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mWebView.destroy();

        super.onDestroy();
    }

    public void onBackPressed() {
        closePage();
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    @SuppressLint({"SetJavaScriptEnabled", "NewApi"})
    private void init() {
        mTopbar = (CustomTopBarNew) findViewById(R.id.broswerTopBar);
        mTopbar.setonTopbarNewLeftLayoutListener(this);
        mTopbar.setTopbarLeftLayout(R.drawable.ship_webview_close, 0, 0);

        mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);
        mWebView = (CustomWebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));
        mWebView.setWebChromeClient(new AppWebChromClient(this,this, FILECHOOSER_RESULTCODE, REQUEST_SELECT_FILE));
        //mWebView.setOnCustomScroolChangeListener(this);

        //js
        BrowserLocaljsObject jsObj = new BrowserLocaljsObject(this);
        mWebView.addJavascriptInterface(jsObj, "local_obj");

        mShareImageView = (ImageView) findViewById(R.id.shareImageView);

        String loadUrl = "";
        String loadData = "";
        String title = "";

        Bundle data = getIntent().getExtras();
        if (data != null && data.size() > 0) {

            //自定义浏览器顶部颜色
            int top_color_id = data.getInt("top_color_id");
            if (top_color_id != 0) {
                mTopbar.setTopbarBackground(top_color_id);
                UtilityBase.setStatusBarRes(this, top_color_id, true);
            } else {
                UtilityBase.setStatusBarRes(this, com.lib.custom.R.drawable.app_status_bar_bg, true);
            }

            if (data.containsKey("title")) {
                title = data.getString("title");
                mShareTitle = title;
                mTopbarTitle = title;
            }

            if (data.containsKey("info")) {
                mShareInfo = data.getString("info");
            }

            if (data.containsKey("need_share")) {
                mNeedShare = data.getBoolean("need_share", false);
            }

            if (data.containsKey("from_type")) {
                mFromType = data.getInt("from_type");
            }

            if (data.containsKey("ObjectID")) {
                mShareObjectID = data.getString("ObjectID");
            }

            if (data.containsKey("ObjectType")) {
                mShareObjectType = data.getInt("ObjectType");
            }

            if (data.containsKey("cover")) {
                mShareCover = data.getString("cover");
            }

            if (data.containsKey("share_url")) {
                mShareUrl = data.getString("share_url");
            }

            if (data.containsKey("url")) {
                String url = data.getString("url");

                HashMap<String, String> maps = new HashMap<String, String>();
                maps.put("UserId", LoginUtil.getUserId());

                loadUrl = UtilityBase.connectParamsUrl(url, maps);
                mShareUrl = loadUrl;

                Utils.initWebViewSettings(mWebView, false);
                showWebViewUrl(loadUrl);
            } else if (data.containsKey("load_data")) {
                loadData = data.getString("load_data");

                Utils.initWebViewSettings(mWebView, true);
                showWebViewLoadData(loadData);
            }
        }

        if (title.length() > 0) {
            mTopbar.setTopbarTitle(title);
        }

        // 是否需要分享
        if (mNeedShare) {
            mShareImageView.setVisibility(View.VISIBLE);
        } else {
            mShareImageView.setVisibility(View.GONE);
        }
    }

    private void closePage() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();

            //mTopbar.setTopbarTitle(mTopbarTitle);
            return;
        }

        finish(true);
    }

    public void showWebViewUrl(String loadUrl) {

        if (!StringUtilBase.stringIsEmpty(loadUrl)) {
            mWebView.loadUrl(loadUrl);
        }
    }

    public void showWebViewLoadData(String loadData) {

        if (!StringUtilBase.stringIsEmpty(loadData)) {
            mWebView.loadData(loadData, "text/html; charset=UTF-8", null);
        }
    }

    // ==================================================
    public void onProgressChanged(WebView view, int newProgress) {
        LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
        mProgressBar.setMax(100);
        if (newProgress < 100) {
            if (mProgressBar.getVisibility() == View.GONE) {
                mProgressBar.setVisibility(View.VISIBLE);
            }
            mProgressBar.setProgress(newProgress);
        } else {
            mProgressBar.setProgress(100);

            Animation animation = AnimationUtils.loadAnimation(this,
                    R.anim.lib_broswer_progress);
            // 运行动画
            mProgressBar.startAnimation(animation);
            // 将 spinner 的可见性设置为不可见状态
            mProgressBar.setVisibility(View.GONE);
        }
    }

    //=====================================
    public void onPageStarted(String url) {
        LogUtilBase.LogD(null, "onPageStarted===>>" + url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>" + url);
        if (!TextUtils.isEmpty(url)) {

            if (url.startsWith("tel:")) {
                Utils.callPhone(AppBroswerActivity.this, url.substring(4, url.length()));
            } else if (url.startsWith("http")) {
                webView.loadUrl(url);
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {
                    webView.loadUrl(url);
                }
            }
        }

        return true;
    }

    public void onPageFinished(String url) {
        LogUtilBase.LogD(null, "onPageFinished===>>" + url);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_TEST)) {
            LogUtilBase.LogD(null, "test success");
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_TEST)) {
            LogUtilBase.LogD(null, "test fail");
        }
    }

    private void clickShare() {

        AppEnterTongJi.clickEvent(48, mShareObjectID);

        String cover = "";

        if (TextUtils.isEmpty(mShareCover)) {
            cover = SdLocal.getAppIconPath(getApplicationContext());
        } else {
            cover = mShareCover;
        }

        // 调用官方sdk分享，可以各种形式
        ShareLib.Share(this, mShareTitle, mShareInfo, cover, mShareUrl, false,
                new CallBack() {
                    @Override
                    public void callBackSuccess(Object obj) {
                        super.callBackSuccess(obj);

                        MyNetUtil.getInstance().requestShare(AppBroswerActivity.this,
                                MyNetUtil.getInstance(), mShareObjectType,
                                mShareObjectID);
                    }
                });
    }

    public void viewClick(View view) {
        int rid = view.getId();
        switch (rid) {
            case R.id.shareImageView:

                clickShare();
                break;

            default:
                break;
        }
    }

    // ================test==========================
    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getTitle(String title) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getVideoSrc(String videoSrc) {
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getHtmlLength(int HtmlLength) {
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getReferrer(String Referrer) {
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getCover(String cover) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getDescription(String Description) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getArticleID(String arg0) {

    }

}
